<template>
    <div class="container">
        <div class="module">
            <p class="title">登录</p>
            <div class="formblock">
                <el-form :model="form" status-icon :rules="rules" ref="formRef">
                    <el-form-item prop="username">
                        <el-input v-model.trim="form.username" size="large" :prefix-icon="User" />
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input type="password" size="large" show-password v-model="form.password" :prefix-icon="Lock" @keyup.enter="onSubmit" />
                    </el-form-item>
                    <el-form-item class="btn">
                        <el-button type="primary" @click="onSubmit">Login</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { reactive, ref, toRefs } from 'vue';
import { login } from '@/api/index'
import router from '@/router/index.js'
import { setCookie } from '@/utils/storage.js'

const formRef = ref(null)
const { form, rules } = toRefs(reactive({
    form: {
        username: '',
        password: ''
    },
    rules: {
        username: [
            { required: 'true', message: '账户不能为空', trigger: 'blur' }
        ],
        password: [
            { required: 'true', message: '密码不能为空', trigger: 'blur' }
        ]
    }
}))

const onSubmit = () => {
    formRef.value.validate(async valid => {
        if (valid) {
            let res = await login(form.value)
            setCookie('userInfo', JSON.stringify(res))
            ElMessage.success('登录成功!')
            setTimeout(() => {
                router.push('/')
            }, 1500)
        }
    })
}
</script>

<style lang="scss" scoped>
.container {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;

    .module {
        min-width: 300px;
        height: auto;
        box-shadow: 0 0 10px #c7c9c7;
        padding: 40px;
        border-radius: 5px;

        .title {
            font-size: 30px;
            width: 100%;
            text-align: center;
            margin-bottom: 30px;
        }

        :deep(.formblock) {
            .el-input__icon {
                font-size: 18px;
            }

            .el-form-item {
                margin-bottom: 25px;
            }

            .btn {
                margin-bottom: 0;

                .el-form-item__content {
                    justify-content: center;
                    margin-top: 15px;

                    .el-button {
                        padding: 18px 23px;
                        font-size: 17px;
                    }
                }
            }
        }
    }
}
</style>